//
//  GroupEditViewController.m
//  FDSMeshLibDemo
//
//  Created by LEIPENG on 2022/6/10.
//

#import "GroupEditViewController.h"
#import "AddNodeViewController.h"
#import "SearchDeviceTableViewCell.h"

@interface GroupEditViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) MeshTool *meshTool;
@property (nonatomic, strong) NSMutableArray *selectArray;
@property (nonatomic, strong) NSMutableArray *groupNodeList;

@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (weak, nonatomic) IBOutlet UIButton *addLightButton;
@property (weak, nonatomic) IBOutlet UIButton *removeLightButton;

@end

@implementation GroupEditViewController

#pragma mark - Initialize
- (void)InitializeCode{
    self.title = @"组别编辑";
    self.meshTool = [MeshTool shareInstance];
    self.selectArray = [NSMutableArray array];
    self.groupNodeList = [NSMutableArray array];
    self.addLightButton.layer.cornerRadius = 22;
    self.addLightButton.layer.masksToBounds = YES;
    self.removeLightButton.layer.cornerRadius = 22;
    self.removeLightButton.layer.masksToBounds = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationRefreshNodes) name:FDS_REFRESH_NODES_STATE object:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self InitializeCode];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self notificationRefreshNodes];
}
- (void)notificationRefreshNodes{
    FDSMeshGroupModel *groupModel = [FDSMeshApi getGroupByAddress:self.address];
    [self.groupNodeList setArray:groupModel.groupDevices];
    [self.selectArray removeAllObjects];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableview reloadData];
    });
}
#pragma mark - UIButton
- (IBAction)clickSelectAllBtn:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected) {
        for (FDSMeshNodeModel *nodeModel in self.groupNodeList) {
            [self.selectArray addObject:nodeModel.macAddress];
        }
    } else {
        [self.selectArray removeAllObjects];
    }
    [self.tableview reloadData];
}
- (IBAction)clickAddLightBtn:(UIButton *)sender{
    AddNodeViewController *viewController = [[AddNodeViewController alloc] init];
    viewController.address = self.address;
    viewController.functionType = FunctionType_AddGroup;
    [self.navigationController pushViewController:viewController animated:YES];
}
- (IBAction)clickRemoveLightBtn:(UIButton *)sender{
    if (self.selectArray.count == 0) {
        [SVProgressHUD showErrorWithStatus:@"未选中设备！"];
    }  else {
        __block NSInteger progressIndex = 0;
        __block NSInteger failedIndex = 0;
        __block NSMutableArray *tempNodeList = [NSMutableArray array];
        NSArray *tempSelectArray = [NSArray arrayWithArray:self.selectArray];
        // 注：此处可以直接把离线的节点过滤掉
        for (NSString *macAddress in tempSelectArray) {
            FDSMeshNodeModel *model = [FDSMeshApi getNodeByMacAddress:macAddress];
            if (model &&
                model.state != FDS_DeviceStateOutOfLine &&
                ![tempNodeList containsObject:model]) {
                [tempNodeList addObject:model];
            }
        }
        [SVProgressHUD showProgress:0 status:[NSString stringWithFormat:@"进度：%ld/%lu，失败：%ld",(long)progressIndex, (unsigned long)tempNodeList.count, (long)failedIndex]];
        FDSMeshGroupModel *groupModel = [FDSMeshApi getGroupByAddress:self.address];
        [FDSMeshApi configSubscribeGroup:tempNodeList groupModel:groupModel isAdd:NO isCompatible:self.meshTool.meshModel.isCompatibleSubscribe progressAction:^(BOOL success, FDSMeshNodeModel * _Nonnull nodeModal) {
            progressIndex++;
            if (!success) {
                failedIndex++;
            }
            CGFloat progressPercent = (CGFloat)progressIndex/tempNodeList.count;
            [SVProgressHUD showProgress:progressPercent status:[NSString stringWithFormat:@"进度：%ld/%lu，失败：%ld",(long)progressIndex, (unsigned long)tempNodeList.count, (long)failedIndex]];
        } resultAction:^(BOOL finish) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (finish) {
                    [self.meshTool refreshNodesAndGroups];
                    self.meshTool.studioModel.meshJson = [FDSMeshApi getCurrentMeshJson];
                    [self.meshTool codingMeshData:self.meshTool.meshModel];
                    [self notificationRefreshNodes];
                    [SVProgressHUD showSuccessWithStatus:@"移除完成"];
                } else {
                    [SVProgressHUD showErrorWithStatus:@"移除失败！"];
                }
            });
        }];
    }
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.groupNodeList.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SearchDeviceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SearchDeviceTableViewCell class])];
    if (!cell){
        cell = [[NSBundle mainBundle] loadNibNamed:@"SearchDeviceTableViewCell" owner:nil options:nil][0];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    FDSMeshNodeModel *nodeModel = self.groupNodeList[indexPath.row];
    cell.titleLabel.text = nodeModel.name;
    cell.subTitleLabel.text = [NSString stringWithFormat:@"%@ - %@", nodeModel.type, nodeModel.macAddress];
    if (nodeModel.state == FDS_DeviceStateOutOfLine) {
        cell.iconImageview.image = [UIImage imageNamed:@"setting_04"];
    } else {
        cell.iconImageview.image = [UIImage imageNamed:@"setting_05"];
    }
    if ([self.selectArray containsObject:nodeModel.macAddress]) {
        cell.selectImageview.image = [UIImage imageNamed:@"setting_02"];
    } else {
        cell.selectImageview.image = [UIImage imageNamed:@"setting_01"];
    }
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    FDSMeshNodeModel *nodeModel = self.groupNodeList[indexPath.row];
    if ([self.selectArray containsObject:nodeModel.macAddress]) {
        [self.selectArray removeObject:nodeModel.macAddress];
    } else {
        [self.selectArray addObject:nodeModel.macAddress];
    }
    [self.tableview reloadData];
}

@end
